/**
 * Project Name:SimonFramework
 * File Name:ImageDownloader.java
 * Package Name:com.simon.framework.image.core.download
 * Date:2016-5-19 下午3:50:22
 * Copyright (c) 2016, simon@cmonbaby.com All Rights Reserved.
 */
package com.cmonbaby.images.core.download;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

/**
 * <p>Author:      Simon
 * <p>QO:          8950764
 * <p>Email:       simon@cmonbaby.com
 * <p>WebSize:     https://www.cmonbaby.com
 * <p>Version:     1.0.0
 * <p>Date:        2020/12/29
 * <p>Description: 提供检索，实现必须是线程安全的
 */
public interface ImageDownloader {

    /**
     * 图片的URI检索 {@link InputStream}
     *
     * @param imageUri 图片的URI
     * @param extra    辅助对象被传递给 DisplayImageOptions.Builder#extraForDownloader(Object)
     *                 DisplayImageOptions.extraForDownloader(Object); 可以为空
     * @return {@link InputStream} 图像流
     * @throws IOException                   如果在获取图像流中发生一些I/O错误
     * @throws UnsupportedOperationException 如果图像URI不支持scheme(协议)
     */
    InputStream getStream(String imageUri, Object extra) throws IOException;

    /** 代表支持schemes(协议)的URI。提供方便的方法来处理schemes和URIs */
    public enum Scheme {
        HTTP("http"), HTTPS("https"), FILE("file"), CONTENT("content"), ASSETS("assets"), DRAWABLE("drawable"), UNKNOWN("");

        private String scheme;
        private String uriPrefix;

        Scheme(String scheme) {
            this.scheme = scheme;
            uriPrefix = scheme + "://";
        }

        /**
         * 定义scheme的URI
         *
         * @param uri URI的scheme检索
         * @return 带Scheme的URI
         */
        public static Scheme ofUri(String uri) {
            if (uri != null) {
                for (Scheme s : values()) {
                    if (s.belongsTo(uri)) {
                        return s;
                    }
                }
            }
            return UNKNOWN;
        }

        private boolean belongsTo(String uri) {
            return uri.toLowerCase(Locale.US).startsWith(uriPrefix);
        }

        /** 添加scheme到路径中 */
        public String wrap(String path) {
            return uriPrefix + path;
        }

        /** 从传入的URI中删除scheme部分(“scheme://”) */
        public String crop(String uri) {
            if (!belongsTo(uri)) {
                throw new IllegalArgumentException(String.format("URI [%1$s] doesn't have expected scheme [%2$s]", uri, scheme));
            }
            return uri.substring(uriPrefix.length());
        }
    }

}

